package com.sunwayworld.basemodule.rm.equipment.io;

import com.sunwayworld.baseline.framework.utils.TemplateExcelHelper;
import com.sunwayworld.basemodule.basedata.exporttemplate.service.LimsGenericTemplateService;
import com.sunwayworld.framework.mybatis.mapper.MatchPattern;
import com.sunwayworld.framework.mybatis.mapper.SearchFilter;
import com.sunwayworld.framework.spring.annotation.GikamBean;
import com.sunwayworld.module.sys.code.bean.CoreCodeBean;
import com.sunwayworld.module.sys.code.service.CoreCodeService;
import org.apache.poi.ss.usermodel.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Component;

import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.nio.file.Path;
import java.util.List;

/**
 * @author xiongym  2020-3-18
 */
@Component(value = "LimsEquipmentExportTemplate")
@GikamBean
public class LimsEquipmentExportTemplate implements LimsGenericTemplateService<String> {

    @Autowired
    @Lazy
    CoreCodeService coreCodeService;

    @Override
    public void initTemplateData(Path path, String id) {
        try {
            InputStream in = new FileInputStream(path.toString());
            Workbook workBook = WorkbookFactory.create(in);
            Sheet sheet = workBook.getSheetAt(0);

            // 根据选择内容填充下拉框
            String[] columns = new String[]{"measureFlag", "equipState", "equipClass", "location"};
            String[] codeCategoryIds = new String[]{"yesorno", "equipState", "eqClass", "equip-location"};
            TemplateExcelHelper.fillSheetSelect(sheet, 1, columns, codeCategoryIds);

            Sheet orgNameSheet = workBook.getSheetAt(1);
            List<CoreCodeBean> useOrgs = coreCodeService.selectListByFilter(SearchFilter.instance().match("codeCategoryId", "equip-useOrg").filter(MatchPattern.EQ));
            for (int i = 0; i < useOrgs.size(); i++) {
                Row row = orgNameSheet.createRow(i + 1);
                Cell cell = row.createCell(0);
                cell.setCellValue(useOrgs.get(i).getCodeName());
            }

            in.close();
            FileOutputStream outputStream = new FileOutputStream(path.toString());
            workBook.write(outputStream);
            outputStream.close();
            workBook.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
